package com.study.messagebus.core

import android.util.ArrayMap
import androidx.lifecycle.*

object LiveDataBus {

    private val liveDataPool = ArrayMap<String, MutableLiveData<*>>()

    //获取一个LiveData实例，如果在liveDataPool存在的话，直接返回，否则创建并返回
    fun <T> of(key: String): MutableLiveData<T> {
        var liveData = liveDataPool[key]
        if (liveData == null) {
            liveData = MutableLiveData<T>()
            liveDataPool[key] = liveData
        }
        return liveData as MutableLiveData<T>
    }

    //事件消费
    fun <T> observe(owner: LifecycleOwner, key: String, observer: Observer<in T>) {
        of<T>(key).observe(owner, observer)
        //注册了观察者的页面，无论数据是否被消费，在页面销毁的时候都要移除liveData
        //因为liveData在消费事件的时候，持有了LifecycleOwner，如果不及时移除，会引起内存泄露
        owner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                when (event) {
                    Lifecycle.Event.ON_DESTROY -> {
                        off(key)
                    }
                    else -> {}
                }
            }
        })
    }

    //取消注册,谁消费事件，谁负责取消注册
    private fun off(key: String) {
        if (liveDataPool.containsKey(key)) {
            liveDataPool.remove(key)
        }
    }
}